package com.example.demo.controller.equipment;

import com.example.demo.domain.equipment.Plan;
import com.example.demo.service.equipment.PlanService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping
@CrossOrigin
public class PlanController {
    @Resource
    @Autowired
    private PlanService planService;

    private List<Plan> planList;

    @PostMapping(value = "/add-plan")
    public Plan addPlan(@RequestBody Plan plan) {
        return planService.addplan(plan);
    }

    @GetMapping(value = "/plan-list")
    public String getPlan(@RequestParam("planId") String planId){
        planList=planService.getPlan(planId);
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("number",planList.size());
        jsonArray.add(jsonObject);
        List<Plan> plans = planList;
        for (Plan temp:plans){
            JSONObject jsonObject1=new JSONObject();
            jsonObject1.put("ticketId",temp.getTicketId());
            jsonObject1.put("planId",temp.getPlanId());
            jsonObject1.put("purchaseItem",temp.getPurchaseItem());
            jsonObject1.put("expectSglPrice",temp.getExpectSglPrice());
            jsonObject1.put("purchaseNum",temp.getPurchaseNum());
            jsonObject1.put("purchaseUnit",temp.getPurchaseUnit());
            jsonObject1.put("expectPrice",temp.getExpectPrice());
            jsonObject1.put("purchaseContract",temp.getPurchaseContract());
            jsonObject1.put("utdPurchaseNum",temp.getUtdPurchaseNum());
            jsonObject1.put("purchaseStatus",temp.getPurchaseStatus());
            jsonArray.add(jsonObject1);
        }
        return jsonArray.toString();
    }

    @GetMapping(value = "/search-plan-by-ticket-id")
    public Plan getplanbyid(@RequestParam("ticketId") Integer id){
        return planService.getPlanbyTicketidMatched(id);
    }

    @PutMapping(value = "/edit-plan")
    public Plan editPlan(@RequestBody Plan plan){
        System.out.print(plan);
        return planService.editPlan(plan);
    }

    @DeleteMapping(value = "/delete-plan-by-id")
    public void deletePlan(@RequestParam("ticketId") Integer id){
        planService.deletePlan(id);
    }
}
